﻿using Base.Entities.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

namespace Base.Common.Converters
{
    public class EnumSourceConverter : ConverterBase
    {
        public Type EnumType { get; set; }

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if (EnumType.IsEnum)
                {
                    var fields = EnumType.GetFields(BindingFlags.Static | BindingFlags.Public);
                    var enumItemType = typeof(EnumItem<>).MakeGenericType(EnumType);
                    var listType = typeof(List<>).MakeGenericType(enumItemType);
                    var list = (IList)Activator.CreateInstance(listType);
                    foreach (var field in fields)
                    {
                        var tempEnum = (Enum)field.GetValue(null);
                        var item = Activator.CreateInstance(enumItemType, tempEnum, tempEnum.GetDescription());
                        list.Add(item);
                    }
                    return list;
                }
            }
            catch (Exception)
            {
                //ignore
            }
            return null;
        }

        public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
